<?
define('SSLIB_Frame', TRUE);
if(!defined("SSLIB_Template")) die("Template class missing");
if(!defined("SSLIB_Request")) die("Request class missing");
class Frame
{
	private $template = null;
	private $count = null;
	private $limit = null;
	private $noneed = false;
	private $data;
	/**
	 * Construct Frame object. Notice: if {limits} not founded in $query, it will be appended to the end of this string!!!
	 *
	 * @param String $query
	 * @param String $count_query
	 * @param Int $limit
	 */
	function __construct($query, $count_query, $limit = 10)
	{
		$this->limit = $limit;
		
		if(!defined("SSLIB_Database")) die("Database class missing");
		
		if(stripos($query, '{limits}') === false)
		{
			$query.=' '.$this->limits();
			//throw new Err('There is no {limits} in query.');
		}
		else 
		{
			$query = str_replace('{limits}', $this->limits(), $query);	
		}
		
		$this->data = Sslib::DB()->Query($query);
		$this->count  = Sslib::DB()->Query($count_query)->Value();
		
		if($this->count < $this->limit) $this->noneed = true;
	}
	function VisualizeData($template, $callback = null)
	{
		return $this->data->Visualize($template, $callback);
	}
	
	private function limits()
	{
		if($this->noneed)	return "";
		extract(Request::Int('o, l'));
		if(!$l) $l = $this->limit;
		if(!isset($o)) $o = 0;
		$o = $o*$l;
		//TODO: поменять способ для работы разных баз. 
		return Sql::Limit($o, $l);
	}
	function PageNumber(){return Request::Int('o');}
	function Navigation($template, $show_next_and_prev = true)
	{
		$this->template = $template;
		//if(!is_dir($this->template)) throw new Err("$template is not directory");
		
		if($this->noneed){	return "";}
		
		$ret = '';
		extract(Request::Int('o, l'));
		if(!$l) $l = $this->limit;
		if($l >= $this->count) return "";
		$urlseparator = '?';
		$pagenum = 0;
		
		
		
		for($i = 0; $i < $this->count; $i+=$l)
		{
			if($pagenum == $o)
				$templ = 'active.htm';
			else 
				$templ = 'normal.htm';
			$ret.=Template::CompileFile(
				array(
					'url'=>Request::Url().$urlseparator."o=$pagenum&l=$l".(Request::RequiredUrl()?'&'.Request::RequiredUrl():''),
					'pagenum'=>($pagenum+1)
				),
				$this->template.$templ);
			$pagenum++;
		}
		if($show_next_and_prev)
		{
			if($o > 0)
			{
				$oo = $o - 1;
				$ret = Template::CompileFile(
				array(
					'url'=>Request::Url().$urlseparator."o=$oo&l=$l".(Request::RequiredUrl()?'&'.Request::RequiredUrl():''),
					'pagenum' => $oo
				), $this->template.'prev.htm').$ret;
			}
			if((($o+1)*$l) < $this->count)
			{
				
				$oo = $o+1;
				$ret.=	Template::CompileFile(
					array(
						'url'=>Request::Url().$urlseparator."o=$oo&l=$l".(Request::RequiredUrl()?'&'.Request::RequiredUrl():''),
						'pagenum'=>($oo+1)
					),
					$this->template.'next.htm')
					;
			}
				
		}
		return str_replace('{framecontent}',$ret,file_get_contents($this->template.'frame.htm'));
		
	}
	public function Count()
	{
		return $this->count;
	}
}
?>